# -*- coding:UTF-8 -*-#

'''
@author: qianwp
'''

from popcan.core.structures import DigitModel,DigitType,Singleton
from popcan.core.net.redisclient import RedisLinker
from popcan.globals.settings import RedisSettings

class DigitManager(Singleton):
    
    '''
        manage digitors caching and sync
    '''
    
    def __init__(self):
        self.syncset = {}
        self.total = 0
    
    def timeout(self,model):
        pass
    
    def sync(self):
        redis = RedisLinker().begin()
        for digitset in self.syncset.values():
            for digitor in digitset.values():
                if digitor.clean:continue
                digitor.update(redis)
                digitor.clean = True
        RedisLinker().end(redis)
    
    def evit(self):
        pass
    
    def getDigitor(self,dtype,uuid):
        return self.syncset.setdefault(dtype,{}).get(uuid,None)
    
    def addDigitor(self,model):
        self.syncset.setdefault(model.dtype(),{})[model.custId()] = model

    def removeDigitor(self,model):
        digitormap = self.syncset.setdefault(model.dtype(),{})
        del digitormap[model.custId()]
    
class CustomerDigitor(DigitModel):
    
    def __init__(self):
        self.cuuid = ''
        self.trackdigit = 0 #总量  关注数量
        self.addtracdigit = 0 #增量
        self.keytrackdigit = 'a0_%s' % self.cuuid
        self.dangledigit = 0 #总量 被关注数量
        self.adddangdigit = 0 #增量
        self.keydangdigit = 'a1_%s' % self.cuuid
        self.interestdigit = 0 #总量 喜欢的作品的数量
        self.addintrdigit = 0 #增量
        self.keyintrdigit = 'a2_%s' % self.cuuid
        
    def load(self):
        self.adddangdigit,self.addintrdigit,self.addtracdigit = 0,0,0
        self.update(RedisClient())
    def uuid(self):
        return self.cuuid
        
    def dtype(self):
        return DigitType.Customer
    
    def update(self,redis):
        self.trackdigit = redis.incr(self.keytrackdigit,self.addtracdigit)
        self.dangledigit = redis.incr(self.keydangdigit,self.adddangdigit)
        self.interestdigit = redis.incr(self.keyintrdigit,self.addintrdigit)

class CompstDigitor(DigitModel):
    
    def __init__(self):
        self.cuuid = ''
        self.interestdigit = 0 #总量  被收藏数量
        self.addintrdigit = 0 #增量
        self.keyintrdigit = 'b0_%s' % self.cuuid
        self.orderdigit = 0 #总量 被下订单数量
        self.addorderdigit = 0 #增量
        self.keyorderdigit = 'b1_5s' % self.cuuid
        
    def uuid(self):
        return self.cuuid

    def dtype(self):
        return DigitType.Compst
    
    def update(self,redis):
        self.interestdigit = redis.incr(self.keyintrdigit,self.addintrdigit)
        self.orderdigit = redis.incr(self.keyorderdigit,self.addorderdigit)